package com.example.framework.common.factory;

import com.example.framework.common.util.GenericUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public abstract class BaseFactory<Type, Concrete extends FactoryConcrete<Type>> implements ApplicationContextAware {

    private final Map<Type, Concrete> concretes = new HashMap<>();

    public Concrete get(Type k) {
        return concretes.get(k);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Concrete> map = applicationContext.getBeansOfType(GenericUtils.getGenericClass(this.getClass(), 1));
        concretes.putAll(map.values().stream().collect(Collectors.toMap(FactoryConcrete::getType, e -> e)));
    }

}